package com.dm.server.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dm.server.dto.Result;
import com.dm.server.entity.RedisData;
import com.dm.server.entity.Shop;
import com.dm.server.mapper.ShopMapper;
import com.dm.server.service.ShopService;
import com.dm.server.utils.CacheClient;
import com.dm.server.utils.RedisConstants;
import com.dm.server.utils.SystemConstants;
import com.dm.server.utils.BloomFilterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static com.dm.server.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {

    @Autowired
    public StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;
    @Resource
    private BloomFilterUtil bloomFilterUtil;

    @Override
    public Result queryById(Long id) {
        // 使用布隆过滤器防止缓存穿透
        Shop shop = cacheClient.queryWithBloomFilter(
            CACHE_SHOP_KEY, id, Shop.class, this::getById, 
            CACHE_SHOP_TTL, TimeUnit.MINUTES, BLOOM_FILTER_SHOP_KEY
        );

        if(shop == null){
            return Result.fail("店铺不存在");
        }
        //返回结果
        return Result.ok(shop);
    }


    public void saveShop2Redis(long id, long expireTime) {
        Shop shop = this.getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusMinutes(expireTime));
        //设置过期时间为，当前时间+额外秒数
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional//这里修改要保障原子性，但是分布式情况下就没办法保障了
    //我们这里用的是一个单体项目进行的，如果你是分布式，比如你这里更新了数据库，删除缓存是另一个系统做的
    //我们用消息队列异步让其他线程做修改缓存的操作。
    //这种情况我们就不是一个单体了，我们要用分布式事物来做！

    //我之前理解的分布式事务使用场景没问题，准确了

    public Result update(Shop shop) {
        //更写shop数据库和缓存业务
        //单体项目用事物控制统一性
        //拿到要更新的商铺的id
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("商铺id不能为空");
        }
        //先更新数据库
        updateById(shop);
        //再删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }


    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，按数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询redis、按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo() // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        // 4.解析出id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }

    /**
     * 初始化布隆过滤器
     * 在系统启动时或数据更新后调用
     */
    public void initBloomFilter() {
        // 获取所有商铺ID
        List<Shop> shops = this.list();
        if (shops != null && !shops.isEmpty()) {
            // 将商铺ID添加到布隆过滤器
            for (Shop shop : shops) {
                bloomFilterUtil.add(BLOOM_FILTER_SHOP_KEY, shop.getId().toString());
            }
            // log.info("商铺布隆过滤器初始化完成，共添加 {} 个商铺ID", shops.size()); // Original code had this line commented out
        }
    }
}




